<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 17/1/17
 * Time: 11:52
 */

namespace app\common\controller;


use app\common\services\LiteBaseService;
use app\home\model\SiteDomain;
use think\Exception;

class LiteBaseWithService extends LiteBase
{
    protected $theme;

    public function __construct()
    {
        parent::__construct();
        if (!IS_CLI) {
            $this->setTheme();
        }
    }

    private function setTheme()
    {
        $siteDomain = SiteDomain::instance();
        $host = ccnn_request_host();
        $siteRow = $siteDomain->where(['domain' => $host])->find();
        if (!empty($siteRow)) {
            $site_id = $siteRow['belong_site_id'];
            $this->view->theme($this->theme = $siteRow['theme']);
        } else {
            $site_id = 0; // 主站
        }
        if ($siteDomain->getSiteId() != $site_id) {
            $siteDomain->setSiteId($site_id);
        }
    }

    protected $_service;
    private $meta_title = '视频下载';
    private $meta_keywords = '视频下载';
    private $meta_description = '视频下载';

    protected function setMetaTitle($title)
    {
        $this->meta_title = $title . SiteDomain::instance()->getCurDomainInfo('seo_suffix');
    }

    protected function setMetaKeywords($keywords)
    {
        $this->meta_keywords = $keywords;
    }

    protected function setMetaDescription($description)
    {
        $this->meta_description = $description;
    }

    protected function setMetaFromModel($model)
    {
        if (!$model) {
            return;
        }
        if (array_key_exists('seo_title', $model)) {
            $this->meta_title = $model['seo_title'] . SiteDomain::instance()->getCurDomainInfo('seo_suffix');
        }
        if (array_key_exists('seo_keywords', $model)) {
            $this->meta_keywords = $model['seo_keywords'];
        }
        if (array_key_exists('seo_desc', $model)) {
            $this->meta_description = $model['seo_desc'];
        }
    }

    public function fetch($template = '', $vars = [], $config = [])
    {
        $this->assign('meta', [
            'title' => $this->meta_title,
            'keywords' => $this->meta_keywords,
            'description' => $this->meta_description,
        ]);
        return parent::fetch($template, $vars, $config); // TODO: Change the autogenerated stub
    }

    protected function setService()
    {
        $this->_service = new LiteBaseService();
    }

    public function _empty($method)
    {
        try {
            if ($this->_service && method_exists($this->_service, $method)) {
                $rt = $this->_service->$method(I('param.'));
                if (is_array($rt)) {
                    return $this->commonData($rt);
                }
                return $rt;
            }
        } catch (Exception $ex) {
            if (IS_AJAX) {
                return $this->commonData([false, $ex->getMessage()]);
            }
            return $ex->getMessage();
        }
    }


}